/**
 * Created by fupeng on 17/3/2.
 */
var config = require('../../config');
var request = require('request');
var member = require('../models/MemberModel');
var OAuth = require('wechat-oauth');
// var oauthDao = require('../dao/Oauth2RedisDao');
var oauthDao = require('../dao/OauthDao');

var client = new OAuth(config.app.appid, config.app.appsecret, function (openid, callback) {
    // 传入一个根据openid获取对应的全局token的方法
    // 在getUser时会通过该方法来获取token
    oauthDao.getOauth(openid, function (message,result) {
        console.log('save access token to database success.');
        return callback(null, result);
    });
}, function (openid, token, callback) {
    // 请将token存储到全局，跨进程、跨机器级别的全局，比如写到数据库、redis等
    // 这样才能在cluster模式及多机情况下使用，以下为写入到文件的示例
    // 持久化时请注意，每个openid都对应一个唯一的token!
    oauthDao.setOauth(openid,token, function (message) {
        console.log('save access token to database success.');
        return callback(message);
    });
});


var sign = require('../../common/utils/sign.js');
var jsapiTicketController = require('./JsapiTicketController');

var queryConfig = function (callback, req) {
    var url = req.protocol + '://' + req.host + req.originalUrl; //获取当前url
    var ret = sign(jsapiTicketController.getJsapiTicket(), url);
    console.log(ret);
    callback(ret);
};

module.exports.getMemberHome = function (req,res){
    var cookie_openid;
    if(req.signedCookies.open_id) {
        cookie_openid = req.signedCookies.open_id;
        queryConfig(function (ret) {
            res.render('memberhome', {
                title: '会员中心',
                layout: false,
                sign_pkg: ret.jsapi_ticket,
                appId: config.app.appid,
                timestamp: ret.timestamp,
                nonceStr: ret.nonceStr,
                signature: ret.signature,
                open_id: cookie_openid,
                sdkKey: config.amap.sdkKey
            });
        }, req);
    }else{

        client.getAccessToken(req.query.code, function (err, result) {
            if (err) {
                res.render('error', {
                    title: '服务器出错',
                    message: '获取accesstoken失败',
                    layout: false
                });
            } else {
               var openid = result.data.openid;
           // var openid ='oSx2pszAztjzEwHKfr7yWhdg2Bz4';
                queryConfig(function (ret) {
                    res.cookie('open_id', openid, {maxAge:1000*60*60*1,signed:true});
                    res.cookie('openid', openid, {maxAge:1000*60*60*1,signed:true});
                    res.render('memberhome', {
                        title: '会员中心',
                        layout: false,
                        sign_pkg: ret.jsapi_ticket,
                        appId: config.app.appid,
                        timestamp: ret.timestamp,
                        nonceStr: ret.nonceStr,
                        signature: ret.signature,
                        open_id: openid,
                        sdkKey: config.amap.sdkKey
                    });
                }, req);
            }
        });
    }
};
module.exports.getChangePhone = function (req,res){
    var open_id = req.query.open_id;
    res.render('changephone',{
        title:'修改手机号',
        layout:false,
        open_id:open_id
    })
};
module.exports.getchangeUser = function (req,res){
    var open_id = req.query.open_id;
    res.render('userchange',{
        title:'更换用户',
        layout:false,
        open_id:open_id
    })
};
module.exports.getMember = function (req,res){

    var open_id = req.signedCookies.open_id;

    member.selectByOpenID(open_id,function(member){
        if(member[0]){
            res.render('member',{
                title:'会员中心',
                layout:false,
                member:member[0]
            })
        }else{
            res.render('login',{
                title:'会员注册',
                layout:false
            })
        }
    })
};
